<template>
  <section class="grant-user">
    <section class="user-main">
      <section class="main-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input v-model.trim="search.userRealname" placeholder="输入姓名搜索" class="search-input" @keyup.enter.native="handleFilter" />
        <section class="search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </section>
      </section>

      <section class="main-buttons">
        <section class="main-buttons-title">
          <span>发放人员设置</span>
        </section>
        <section class="main-buttons-btns">
          <el-button v-if="active == 'GIDS01' || active=='all'" style="margin-left: 10px" @click="handleBatch">批量发放</el-button>
          <el-button v-if="active == 'GIDS01' || active=='all'" style="margin-left: 10px" @click="getCountFun">全部发放</el-button>
          <el-button style="margin-left: 10px" @click="handleDownload">下载批量导入模版</el-button>
          <el-button style="margin-left: 10px" @click="handleUpload">批量导入</el-button>
          <el-button style="margin-left: 10px" @click="handleSelect">选择人员</el-button>
          <el-button style="padding: 10px 30px" @click="handleCancel">返回</el-button>
        </section>
      </section>

      <section class="main-tab">
        <el-tabs v-model="active" @tab-click="handleTabClick">
          <el-tab-pane v-for="item in types" :key="item.id" :label="item.name" :name="item.id" />
        </el-tabs>
      </section>
      <section class="main-table">
        <v-table :key="time" :list="list" tag="grantuser" :list-loading="loading" :filter-column="filtercolumn" @handleSelectionChange="handleSelectionChange">
          <el-table-column align="center" label="操作">
            <template slot-scope="{ row }">
              <el-button v-if="row.status == 'GIDS01'" type="text" size="mini" @click="handleGrant(row)">发放福利</el-button>
              <el-button v-if="row.status !== 'GIDS03'" type="text" size="mini" @click="handleDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </v-table>
        <pagination v-if="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </section>
    </section>

    <v-upload v-if="showupload" :id="id" @success="handleUploadSuccess" @cancel="handleUploadCancel" />
    <v-user v-if="showuser" :id="id" :type="t" @comit="handleUserComit" @cancel="handleUserCancel" />
  </section>
</template>
<script>
import elDragDialog from '@/directive/el-drag-dialog'
import permission from '@/directive/permission/index.js'
import Pagination from '@/components/Pagination'
import VTable from '@/components/Table'
import CryptoJS from '@/utils/aesJiaJM'
import { queryPage, getDictByCode, update, del, insert, grant } from './../api/record'
import VUpload from './../components/upload'
import VUser from './../components/user'
import { exportSign } from '@/utils/fileImportOrExportSign'

export default {
  name: 'GrantUser',
  components: { VUpload, VUser, Pagination, VTable },
  directive: { permission, elDragDialog },
  data() {
    return {
      state: 'create',
      loading: false,
      search: {
        userRealname: '',
        phoneNumber: ''
      },
      list: [],
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      selection: [],
      dict: {
        numberPOOLSTATUS: [], //
        ZPID: []
      },
      t: '',
      id: '',
      showupload: false,
      showuser: false,
      types: [
        {
          name: '全部',
          id: 'all'
        },
        {
          name: '待发放',
          id: 'GIDS01'
        },
        {
          name: '待领取',
          id: 'GIDS02'
        },
        {
          name: '已领取',
          id: 'GIDS03'
        }
      ],
      active: 'all',
      userTotal: 0,
      time: new Date()
    }
  },
  created() {
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.t = this.$route.query.t
    if (this.$route.query.id) {
      this.id = this.$route.query.id
      this.getList()
    } else {
      this.$message({
        showClose: true,
        message: '参数异常！',
        type: 'warning',
        onClose: () => {
          this.$router.back()
        }
      })
    }
  },
  methods: {
    handleBatch() {
      if (this.selection.length == 0) {
        this.$message.error('请选择要发放的用户')
        return
      }
      const user =	this.selection.find(a => {
        return a.statusValue != '待发放'
      })
      if (user) {
        this.$message.error(`[${user.userRealname}]的状态为：[${user.statusValue}]`)
        return
      }
      this.$confirm(`确定给${this.selection.length}位职工发放吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        const ids = []
        this.selection.forEach(element => {
          ids.push(element.id)
        })
        return new Promise((resolve, reject) => {
          grant({ ids: ids.join(','), status: 'GIDS02', giveId: this.id }).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '发放成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => { })
    },
    getCountFun() {
      return new Promise((resolve, reject) => {
        var query = {
          giveId: this.id,
          queryFlag: 0,
          page: this.listQuery.page,
          pageSize: this.listQuery.limit,
          status: 'GIDS01'
        }
        queryPage(query).then((res) => {
          if (res.data.code == '200') {
            this.userTotal = res.data.data.total
            if (this.userTotal > 0) {
              this.handleAll()
            } else {
              this.$message.error('当前没有待发放人员！')
            }
          }
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },
    handleAll() {
      this.$confirm(`共有${this.userTotal}位待发放职工，确定发放吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          grant({ status: 'GIDS02', giveId: this.id }).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '发放成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => { })
    },
    filtercolumn(scope, item) {
      if (item === 'userStatus') {
        return scope.row[item] || '--'
      } else if (item === 'isDirectional') {
        return scope.row[item] === 'ZPID02' ? '否' : '是'
      } else {
        return scope.row[item] || '--'
      }
    },

    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code).then(res => {
          this.dict[code] = (res.data.data && res.data.data.length > 0) ? res.data.data[0].list : []
        }).catch(error => {
          reject(error)
        })
      })
    },

    /**
     * 选项卡切换
     */
    handleTabClick(tab, event) {
      this.listQuery.page = 1
      this.getList()
    },

    handleDownload() {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = '/API-ENTERPRISE-BACKEND/backend/giveInfoDetail/downloadGiveInfoDetailTemplate' + exportSign().paramStr
      link.setAttribute('download', '模版.xls')
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    handleUpload() {
      this.showupload = true
    },

    handleUploadCancel() {
      this.showupload = false
    },

    handleUploadSuccess() {
      this.getList()
    },

    handleSelect() {
      this.showuser = true
    },

    handleUserCancel() {
      this.showuser = false
    },

    handleUserComit({ data, number }) {
      if (data && data.length > 0) {
        const list = []
        data.forEach(a => {
          list.push(a.id)
        })
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          insert({
            userIds: list.join(','),
            giveId: this.id,
            giveNumber: number
          }).then(() => {
            loading.close()
            this.dialogFormVisible = false
            this.$message({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.showuser = false
            this.getList()
          }).catch(error => {
            reject(error)
            loading.close()
          })
        })
      }
    },

    handleCancel() {
      this.$router.push({
        path: this.$filterPath('index'),
        query: { t: this.t }})
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleReset() {
      this.listQuery.page = 1
      for (const i in this.search) {
        this.search['' + i + ''] = ''
      }
      this.getList()
    },

    handleSelectionChange(arr) {
      this.selection = arr
    },

    handleGrant(row) {
      this.$confirm('确定发放福利给该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          grant({ ids: row.id, status: 'GIDS02', giveId: this.id }).then(() => {
            loading.close()
            this.$message({
              title: '成功',
              message: '发放成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      }).catch(() => { })
    },

    handleDelete(ids) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          del(ids).then(() => {
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            reject(error)
          })
        })
      }).catch(() => { })
    },

    handleCanceledit(row) {
      row.number = row.giveNumber
      row.edit = false
    },

    handleComitedit(row) {
      row.giveNumber = row.number
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      const {
        id,
        giveNumber
      } = row
      return new Promise((resolve, reject) => {
        update({
          id,
          giveNumber
        }).then(() => {
          loading.close()
          this.dialogFormVisible = false
          this.$message({
            title: '成功',
            message: '设置成功',
            type: 'success',
            duration: 2000
          })
          row.edit = false
          this.getList()
        }).catch(error => {
          reject(error)
          loading.close()
        })
      })
    },

    getList(obj) {
      this.loading = true
      var query = {
        giveId: this.id,
        queryFlag: 0,
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        status: this.active === 'all' ? '' : this.active,
        userRealname: this.search.userRealname,
        phoneNumber: CryptoJS.$aesJiaM(this.search.phoneNumber)
      }
      return new Promise((resolve, reject) => {
        queryPage(query).then(({ data }) => {
          const list = data.data.rows
          if (list && list.length > 0) {
            this.list = list.map(a => {
              return {
                ...a,
                number: a.giveNumber,
                JPhoneNumber: a.phoneNumber,
                edit: false
              }
            })
          } else {
            this.list = []
          }
          this.total = data.data.total
          // console.log("list",this.list)
          this.loading = false
        }).catch(error => {
          reject(error)
          this.loading = false
        })
      })
    }
  }
}
</script>
<style lang="scss">
@import '@/styles/mixin.scss';
.grant-user {
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .user-main {
    position: absolute;
    top: 10px;
    left: 0;
    right: 0;
    bottom: 10px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: auto;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    .main-search {
      background-color: #fff;
      padding: 0 10px;
      .svg-container {
        color: #bfced6;
        display: inline-block;
      }
      .search-input {
        width: 60%;
        position: relative;
        &:after {
          content: '';
          position: absolute;
          left: -25px;
          right: 0;
          bottom: 8px;
          height: 1px;
          background: rgba(226, 227, 232, 1);
        }
        input {
          outline: none;
          background: transparent;
          border: none;
          outline: medium;
          padding: 0;
          &:focus {
            outline: none;
            background-color: transparent;
          }
        }
      }
      .search-btn {
        display: inline-block;
        float: right;
        .el-button.is-round {
          padding: 10px 30px;
          margin-right: 34px;
        }
        .search-more {
          font-size: 14px;
          font-weight: 500;
          @include font-color($mainColor);
          cursor: pointer;
          margin-left: 10px;
        }
      }

      &.merge {
        height: 50px;
        line-height: 50px;
      }
    }

    .main-buttons {
      display: flex;
      line-height: 36px;
      margin-top: 10px;
      .main-buttons-title {
        flex: 1;
        height: 36px;
        line-height: 36px;
        font-size: 16px;
        font-weight: bold;
        color: rgba(51, 51, 51, 1);
      }
    }

    .main-tab {
      width: 100%;
      margin-top: 10px;
      padding: 0 10px;
      background-color: #fff;
      display: flex;
      border-radius: 4px;
      .el-tabs__nav-wrap::after {
        display: none;
      }
      .el-tabs__header {
        margin: 0;
      }
    }

    .main-table {
      .table-search {
        margin-bottom: 10px;
      }
      .edit-input {
        padding-right: 40px;
      }
      .cancel-btn {
        position: absolute;
        right: 15px;
        top: 10px;
      }
    }
  }
}
</style>
